package com.usefullc.common.util.jdbc;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtils {
    private final static Logger bisLog = org.slf4j.LoggerFactory.getLogger("bis");
    protected final static Logger log = org.slf4j.LoggerFactory.getLogger(JdbcUtils.class);

    public static int execute(DataSourceConfig dbConfigure, String sql) {
        bisLog.info("param sql=" + sql);
        sql = sql.replaceAll("\\n", "");
        int result = 0;
        try {
            Class.forName(dbConfigure.getDriver());
            // 获取数据库连接
            Connection conn = DriverManager.getConnection(dbConfigure.getUrl(), dbConfigure.getUser(), dbConfigure.getPassword());

            // 使用Connection来创建一个Statment对象
            Statement stmt = conn.createStatement();

            // 执行DDL,创建数据表
            String[] split = sql.split(";");
            if (split.length > 1) {
                for (int i = 0; i < split.length; i++) {
                    String s = split[i];
                    if (StringUtils.isNotEmpty(s)) {
                        stmt.addBatch(s);
                        bisLog.info("sql=" + s);
                    }
                }
                int[] results = stmt.executeBatch();
                result = results[0];
            } else {
                result = stmt.executeUpdate(sql);
                bisLog.info("result=" + result);
            }
            stmt.close();
            conn.close();

        } catch (Exception e) {
            log.error("sql=" + sql);
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException){
                log.error("sql error",e);
            }else{
                throw new RuntimeException("execute sql failed! ", e);
            }
        }
        return result;
    }

    public static List<Map<String,Object>> query(DataSourceConfig dbConfigure, String sql,List<String> columns) {
        bisLog.info("param sql=" + sql);
        List<Map<String,Object>> dataList = new ArrayList<>();
        try {
            Class.forName(dbConfigure.getDriver());
            // 获取数据库连接
            Connection conn = DriverManager.getConnection(dbConfigure.getUrl(), dbConfigure.getUser(), dbConfigure.getPassword());

            // 使用Connection来创建一个Statment对象
            Statement stmt = conn.createStatement();
            ResultSet resultSet = stmt.executeQuery(sql);
            while(resultSet.next()){
                Map<String,Object> valueMap = new LinkedHashMap<>();
                dataList.add(valueMap);
                for (String column : columns) {
                    Object value = resultSet.getObject(column);
                    valueMap.put(column,value);
                }
            }
        } catch (Exception e) {
            log.error("sql=" + sql);
            throw new RuntimeException("execute query sql failed! ", e);
        }
        return dataList;
    }

    public static void main(String[] args) {
        String sql = "aaa;bbb;";
        String[] split = sql.split(";");
        if (split.length > 1) {
            for (int i = 0; i < split.length; i++) {
                String s = split[i];
                if (StringUtils.isNotEmpty(s)) {
                    bisLog.info("sql=" + s);
                }
            }
        }
    }
}

